<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
    const list = [
      { id: '1001', manager: '管理员', name: '行政部', pid: '' },
      { id: '1002', manager: '管理员', name: '财务部', pid: '' },
      { id: '1003', manager: '管理员', name: '人事部', pid: '' },
      { id: '1004', manager: '巴斯慧', name: '上海事业部', pid: '1001' },
      { id: '1005', manager: '孙财', name: '财务核算部', pid: '1002' },
      { id: '1006', manager: '张飞', name: '税务管理部', pid: '1002' }
    ]
    // 创建map空对象 建立映射关系
    const map={}
    list.forEach(item=>{
      item.children = []
      map[item.id] = item
    })
    console.log('list:',list)
    console.log('map:',map)
    // 遍历数组 生成树形结构
    const treeList = []
    list.forEach(item=>{
      if(item.pid){
        // pid有数据 是二级
        console.log(map[item.pid])
        const parent = map[item.pid] //遍历出所有一级
        parent.children.push(item)
      }else{
        // pid没有数据 是一级
        treeList.push(item)
      }
    })
    console.log('treeList:',treeList)
  </script>
</body>
</html>